<template>
  <div class="course-detail-container">
    <div v-if="course" class="course-content">
      <div class="course-header">
        <h1>{{ course.title }}</h1>
        <div class="course-meta">
          <span class="instructor">讲师: {{ course.instructor }}</span>
          <span class="level">难度: {{ getLevelText(course.level) }}</span>
          <span class="duration">时长: {{ course.duration }}</span>
        </div>
      </div>

      <div class="main-content">
        <div class="video-section">
          <div class="video-player">
            <video
              v-if="currentVideo"
              ref="videoPlayer"
              controls
              @timeupdate="handleTimeUpdate"
            >
              <source :src="currentVideo.url" type="video/mp4">
              您的浏览器不支持视频播放。
            </video>
            <div v-else class="video-placeholder">
              <p>选择章节开始学习</p>
            </div>
          </div>
          <div class="video-info" v-if="currentVideo">
            <h3>{{ currentVideo.title }}</h3>
            <p>{{ currentVideo.description }}</p>
          </div>
        </div>

        <div class="course-chapters">
          <h2>课程章节</h2>
          <div class="chapter-list">
            <div v-for="chapter in course.chapters" :key="chapter.id" class="chapter">
              <div class="chapter-header" @click="toggleChapter(chapter.id)">
                <h3>{{ chapter.title }}</h3>
                <span class="toggle-icon">{{ expandedChapters.includes(chapter.id) ? '−' : '+' }}</span>
              </div>
              <div class="chapter-lessons" v-show="expandedChapters.includes(chapter.id)">
                <div
                  v-for="lesson in chapter.lessons"
                  :key="lesson.id"
                  class="lesson"
                  :class="{ active: currentVideo?.id === lesson.id }"
                  @click="playVideo(lesson)"
                >
                  <span class="lesson-title">{{ lesson.title }}</span>
                  <span class="lesson-duration">{{ lesson.duration }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="course-details">
        <div class="tabs">
          <button
            v-for="tab in tabs"
            :key="tab.id"
            :class="{ active: activeTab === tab.id }"
            @click="activeTab = tab.id"
          >
            {{ tab.name }}
          </button>
        </div>

        <div class="tab-content">
          <div v-if="activeTab === 'description'" class="course-description">
            <h2>课程介绍</h2>
            <div v-html="course.description"></div>
          </div>

          <div v-if="activeTab === 'materials'" class="course-materials">
            <h2>课程资料</h2>
            <div class="materials-list">
              <div v-for="material in course.materials" :key="material.id" class="material-item">
                <span>{{ material.name }}</span>
                <a :href="material.url" download>下载</a>
              </div>
            </div>
          </div>

          <div v-if="activeTab === 'comments'" class="course-comments">
            <h2>学员评价</h2>
            <div class="comments-list">
              <div v-for="comment in comments" :key="comment.id" class="comment">
                <div class="comment-header">
                  <img :src="comment.avatar" :alt="comment.username" class="avatar">
                  <div class="comment-info">
                    <span class="username">{{ comment.username }}</span>
                    <span class="rating">
                      <i v-for="n in 5" :key="n" class="fas fa-star" :class="{ filled: n <= comment.rating }"></i>
                    </span>
                  </div>
                </div>
                <p class="comment-content">{{ comment.content }}</p>
                <span class="comment-date">{{ formatDate(comment.date) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div v-else class="loading">
      <p>加载中...</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useCourseStore } from '../../stores/course.store'

const route = useRoute()
const courseStore = useCourseStore()

const course = ref(null)
const currentVideo = ref(null)
const expandedChapters = ref([])
const activeTab = ref('description')
const comments = ref([])
const videoPlayer = ref(null)

const tabs = [
  { id: 'description', name: '课程介绍' },
  { id: 'materials', name: '课程资料' },
  { id: 'comments', name: '学员评价' }
]

const getLevelText = (level: string) => {
  const levelMap = {
    beginner: '入门',
    intermediate: '中级',
    advanced: '高级'
  }
  return levelMap[level] || level
}

const toggleChapter = (chapterId: string) => {
  const index = expandedChapters.value.indexOf(chapterId)
  if (index === -1) {
    expandedChapters.value.push(chapterId)
  } else {
    expandedChapters.value.splice(index, 1)
  }
}

const playVideo = (lesson: any) => {
  currentVideo.value = lesson
  if (videoPlayer.value) {
    videoPlayer.value.currentTime = 0
  }
}

const handleTimeUpdate = () => {
  if (videoPlayer.value && currentVideo.value) {
    courseStore.updateProgress({
      courseId: course.value.id,
      lessonId: currentVideo.value.id,
      progress: videoPlayer.value.currentTime
    })
  }
}

const formatDate = (date: string) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

onMounted(async () => {
  try {
    const courseId = route.params.id as string
    course.value = await courseStore.getCourseDetail(courseId)
    comments.value = await courseStore.getCourseComments(courseId)
    
    // 默认展开第一个章节
    if (course.value.chapters.length > 0) {
      expandedChapters.value = [course.value.chapters[0].id]
    }
  } catch (error) {
    console.error('Failed to load course details:', error)
  }
})
</script>

<style scoped>
.course-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.course-header {
  margin-bottom: 2rem;
}

.course-header h1 {
  font-size: 2rem;
  color: #333;
  margin-bottom: 1rem;
}

.course-meta {
  display: flex;
  gap: 2rem;
  color: #666;
}

.main-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 2rem;
  margin-bottom: 2rem;
}

.video-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.video-player {
  width: 100%;
  aspect-ratio: 16/9;
  background: #000;
}

.video-player video {
  width: 100%;
  height: 100%;
}

.video-placeholder {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
}

.video-info {
  padding: 1.5rem;
}

.course-chapters {
  background: white;
  border-radius: 8px;
  padding: 1.5rem;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.chapter {
  margin-bottom: 1rem;
}

.chapter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem;
  background: #f5f5f5;
  border-radius: 4px;
  cursor: pointer;
}

.chapter-header h3 {
  margin: 0;
  font-size: 1rem;
}

.toggle-icon {
  font-size: 1.2rem;
}

.chapter-lessons {
  padding: 0.5rem 0;
}

.lesson {
  display: flex;
  justify-content: space-between;
  padding: 0.75rem 1rem;
  cursor: pointer;
  border-radius: 4px;
}

.lesson:hover {
  background: #f5f5f5;
}

.lesson.active {
  background: #e8f5e9;
  color: #4CAF50;
}

.tabs {
  display: flex;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.tabs button {
  padding: 0.75rem 1.5rem;
  border: none;
  background: none;
  cursor: pointer;
  font-size: 1rem;
  color: #666;
  border-bottom: 2px solid transparent;
}

.tabs button.active {
  color: #4CAF50;
  border-bottom-color: #4CAF50;
}

.tab-content {
  background: white;
  border-radius: 8px;
  padding: 1.5rem;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.materials-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.material-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem;
  background: #f5f5f5;
  border-radius: 4px;
}

.material-item a {
  color: #4CAF50;
  text-decoration: none;
}

.comments-list {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.comment {
  border-bottom: 1px solid #eee;
  padding-bottom: 1rem;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 0.5rem;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.comment-info {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: bold;
}

.rating {
  color: #ffd700;
}

.comment-date {
  color: #666;
  font-size: 0.9rem;
}

.loading {
  text-align: center;
  padding: 2rem;
}
</style>